package com.pine.dbant.core;

import com.pine.dbant.common.context.AppContext;
import com.pine.dbant.common.plugin.PluginConfiguration;
import com.pine.dbant.common.plugin.PluginFactory;
import com.pine.dbant.common.store.CacheStore;
import com.pine.sunflower.core.LifeCycledAdapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.List;

/**
 * @author xiaoyuan
 * @create 2022/11/29 15:00
 **/
@Configuration
@Slf4j
@AutoConfigureAfter(PluginConfiguration.class)
public class DbantBootstrapper extends LifeCycledAdapter implements ApplicationRunner, DisposableBean {


    private final ObjectProvider<List<PluginConfiguration>> pluginsProvider;

    @Autowired
    private PluginFactory pluginFactory;

    @Autowired
    private CacheStore cacheStore;

    public DbantBootstrapper(ObjectProvider<List<PluginConfiguration>> pluginsProvider){
        this.pluginsProvider = pluginsProvider;
    }


    @Override
    public void doInit() {
        List<PluginConfiguration> pluginConfigurations = pluginsProvider.getIfAvailable(Collections::emptyList);

        if (CollectionUtils.isEmpty(pluginConfigurations)) {
            log.warn("未发现插件");
        }
        if (CollectionUtils.isNotEmpty(pluginConfigurations)) {
            pluginConfigurations.forEach(pluginConfiguration -> pluginConfiguration.registerPlugin().register(pluginFactory, AppContext.getConfiguration(),cacheStore ));
        }
    }

    @Override
    public void doStop() {

    }

    @Override
    public void destroy() throws Exception {
        stop();
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        init();
    }
}
